package com.yundou.www.wrpc.core.util;

import org.apache.commons.lang3.StringUtils;

import java.io.File;

import java.lang.annotation.Annotation;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author wangweiwei
 * @since 2021/7/19
 */
public final class ClassLoadUtil {
    static Set<Class<?>> classSet = new HashSet<Class<?>>(16);

    /**
     * 获取类加载器
     */
    public static ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类
     */
    public static Class<?> loadClass(String className, boolean isInitialized) {
        Class<?> cls;
        try {
            cls = Class.forName(className, isInitialized, getClassLoader());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return cls;
    }


    public static List<Class> find(String packageName, Class tClass) {
        if (Objects.isNull(tClass)) {
            return Collections.emptyList();
        }

        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();

                if (url != null) {
                    String protocol = url.getProtocol();
                    if (protocol.equals("file")) {
                        String packagePath = url.getPath().replaceAll("%20", " ");
                        addClass(classSet, packagePath, packageName, tClass);
                    } else if (protocol.equals("jar")) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if (jarURLConnection != null) {
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if (jarFile != null) {
                                Enumeration<JarEntry> jarEntries = jarFile.entries();
                                while (jarEntries.hasMoreElements()) {
                                    JarEntry jarEntry = jarEntries.nextElement();
                                    String jarEntryName = jarEntry.getName();
                                    if (jarEntryName.endsWith(".class")) {
                                        String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                        System.out.println(className);
                                        doAddClass(classSet, className, tClass);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
        return new ArrayList<>(classSet);

    }

    private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName, Class tClass) {
        File[] files = new File(packagePath).listFiles(file -> (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory());
        for (File file : files) {
            String fileName = file.getName();

            if (file.isFile()) {
                String className = fileName.substring(0, fileName.lastIndexOf("."));

                if (StringUtils.isNotEmpty(packageName)) {
                    className = packageName + "." + className;
                }
                doAddClass(classSet, className, tClass);
            } else {
                String subPackagePath = fileName;
                if (StringUtils.isNotEmpty(packagePath)) {
                    subPackagePath = packagePath + "/" + subPackagePath;
                }
                String subPackageName = fileName;
                if (StringUtils.isNotEmpty(packageName)) {
                    subPackageName = packageName + "." + subPackageName;
                }
                addClass(classSet, subPackagePath, subPackageName, tClass);
            }
        }
    }


    private static void doAddClass(Set<Class<?>> classSet, String className, Class tClass) {
        Class<?> cls = loadClass(className, false);

        if ("com.yundou.www.wrpc.core.face.impl.UserServiceImpl".equals(className)) {
            System.out.println("0000" + className);
        }
        Annotation annotation = cls.getAnnotation(tClass);
        if (Objects.nonNull(annotation)) {
            classSet.add(cls);
        }

    }
}
